import pygame
import random

# 初始化 Pygame
pygame.init()

# 设置游戏窗口大小
width, height = 800, 600
win = pygame.display.set_mode((width, height))
pygame.display.set_caption("飞机游戏")

# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)

# 定义飞机
class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("0_Hello_Python\\player.png")  # 请提供飞机图片文件
        self.image = pygame.transform.scale(self.image, (50, 50))  # 调整大小为50x50
        self.rect = self.image.get_rect()
        self.rect.center = (width // 2, height - 50)
        self.speed = 5

    def move(self, keys):
        if keys[pygame.K_LEFT] and self.rect.x > 0:
            self.rect.x -= self.speed
        if keys[pygame.K_RIGHT] and self.rect.x < width - self.rect.width:
            self.rect.x += self.speed

# 定义敌人
class Enemy(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.image.load("0_Hello_Python\\enemy.png")  # 请提供敌人图片文件
        self.image = pygame.transform.scale(self.image, (50, 50))  # 调整大小为50x50
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(0, width - self.rect.width)
        self.rect.y = random.randint(-100, -40)
        self.speed = random.randint(1, 5)

    def move(self):
        self.rect.y += self.speed
        if self.rect.y > height:
            self.rect.y = random.randint(-100, -40)
            self.rect.x = random.randint(0, width - self.rect.width)

# 创建精灵组
all_sprites = pygame.sprite.Group()
enemies = pygame.sprite.Group()

# 创建玩家
player = Player()
all_sprites.add(player)

# 创建敌人
for _ in range(10):
    enemy = Enemy()
    all_sprites.add(enemy)
    enemies.add(enemy)

# 游戏主循环
clock = pygame.time.Clock()
running = True

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    keys = pygame.key.get_pressed()
    player.move(keys)

    # 更新敌人
    for enemy in enemies:
        enemy.move()

    # 检测碰撞
    hits = pygame.sprite.spritecollide(player, enemies, False)
    if hits:
        running = False

    # 清屏
    win.fill(white)

    # 绘制所有精灵
    all_sprites.draw(win)

    # 更新显示
    pygame.display.flip()

    # 控制帧率
    clock.tick(30)

# 退出游戏
pygame.quit()
